package linuxbox.download.taglib;

import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;
import java.util.*;

import linuxbox.BoxStatic;
import linuxbox.download.logic.*;
import linuxbox.download.bean.*;

/**
 * This class displays a department list.
 */
public class DlCatList extends TagSupport {
  protected String listType = null;
  protected int selected = -1;

  public int doStartTag() throws JspException {
    try {
      DownLoadManager dlm = DownLoadManager.getInstance();
      Iterator ids = dlm.getAllDlCats();

      JspWriter out = pageContext.getOut();

      DlCatObject obj = null;
      DlCatKey key = null;

      if ("all".equals(listType)) {
        StringBuffer retVal = new StringBuffer();

        while (ids.hasNext()) {
          key = (DlCatKey)ids.next();
          obj = dlm.getDlCat(key);

          retVal.append("<OPTION value=" + obj.getID());

          if (obj.getID() == selected) {
            retVal.append(" SELECTED");
          }

          retVal.append(">" + obj.getName() + "</OPTION>");
        }
        out.println(retVal.toString());
      } else if ("table".equals(listType)) {
        StringBuffer retVal = new StringBuffer();

        int i = 0;
        while (ids.hasNext()) {
          key = (DlCatKey)ids.next();
          obj = dlm.getDlCat(key);

          retVal.append("<TR");

          if ((i % 2) != 0)
            retVal.append(" bgcolor=\"#E0E0E0\">");
          else
            retVal.append(">");

          retVal.append("<TD><A href=\""+BoxStatic.servletDir+"DlCatEditAction?DL_CAT_ID="
            + obj.getID() + "\">" + obj.getName() + "</A></TD>");
          retVal.append("<TD>" + obj.getDir() + "</TD>");
          retVal.append("<TD><a href=\""+BoxStatic.servletDir+"DlCatDelAction?DL_CAT_ID="
            + obj.getID() + "\">Delete</a></TD>");
          retVal.append("</TR>");

          i++;
        }
        out.println(retVal.toString());
      }

      out.flush();
    } catch(Exception e) {
      BoxStatic.logger.debug("Failed to get all users");
      e.printStackTrace();
      throw new JspException(e.getMessage());
    }

    return SKIP_BODY;
  }

  public void setListType(String aValue) {
    listType = aValue;
  }

  public void setSelected(String aValue) {
    selected = Integer.parseInt(aValue);
  }
}
